<template>
  <view class="page">
    <slot :data="currentSelect">
      <view class="select-content">
        <view>
          <u-text
            color="#fff"
            :text="currentSelect.shortName || defaultTipText"
          />
        </view>
        <u-icon name="arrow-down" size="26rpx" color="#fff" />
      </view>
    </slot>
  </view>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import type { TenantAppType, TenantTreeNode } from './TreeTyping'

import { getTenantListApi, treeFilter } from './service'
import { find, flattenDeep, map } from 'lodash-es'
import { appStore, locationStore } from '@/store/modules'

@Component({ name: 'TenantSelect' })
export default class TenantSelect extends Vue {
  @Prop({ type: String, default: '请选择' })
  defaultTipText!: string

  currentSelect: TenantAppType = {} as TenantAppType

  public sourceData: TenantTreeNode = {} as TenantTreeNode

  get sysTenantId() {
    return appStore.initDefaultTenant
  }

  @Watch('sysTenantId')
  onChange(val: string) {
    if (val === this.currentSelect.tenantId) return
    this.initTenant()
  }

  get tenantTreeList() {
    return treeFilter(this.sourceData)
  }

  async created() {
    // this.sourceData = await getTenantListApi()
    // await this.initTenant()
  }

  /**
   * 初始化租户
   */
  async initTenant() {
    // 将存在tenant的地址提取出来
    const treeFlatMap = (nodes: TenantTreeNode[]): TenantTreeNode[] => {
      return nodes.flatMap(({ children = [], ...attrs }) => [
        attrs,
        ...treeFlatMap(children)
      ])
    }

    const collection: TenantTreeNode[] = treeFlatMap(this.tenantTreeList)

    const treeMapTenants = flattenDeep(
      map(collection, ({ tenantApps = [] }) => tenantApps)
    )
    if (this.sysTenantId) {
      const node = find(treeMapTenants, ['tenantId', this.sysTenantId])
      if (node) {
        this.currentSelect = node
        this.$emit('init:select', node)
        return
      }
    }

    // 根据定位查找
    try {
      const { countyId } = await locationStore.getLocation()
      const node = collection.find(({ positionId }) => positionId === countyId)

      if (!node?.tenantApps) throw Error('No Node')
      if (!this.currentSelect?.tenantId) {
        this.currentSelect = node.tenantApps[0]
        appStore.setLocationTenant(node.tenantApps[0]?.tenantId)
        this.$emit('init:select', node.tenantApps[0])
      }
    } catch (e) {
      // 查找失败进入默认租户查找（也不存在的话取第一项）
      const node = find(treeMapTenants, ['tenantId', '99']) || treeMapTenants[0]
      if (!this.currentSelect?.tenantId) {
        this.currentSelect = node
        appStore.setLocationTenant(node.tenantId)
        this.$emit('init:select', node)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-content {
  display: flex;
  align-items: center;
  font-size: $font-size-base;

  view {
    margin-right: 8rpx;
  }
}
</style>
